import AppPortal from "@/components/AppPortal"
import { offActions } from "@/store/offSlice"
import { useAppSelector, useAppDispatch } from "@/utils/hooks"
import styles from './styles.module.less'
import Content from "./Content"
import { useEffect, useState } from "react"
import { getClassNames, Icon } from "magic-ui-react"
import { CSSTransition } from "react-transition-group"
import './styles.less'
import { icons } from "./cons"
import { isEmpty } from "lodash"
import { appConfigActions } from "@/store/appConfigSlice"
import moment from "moment"

/**
 * 页面分类
 * @returns ReactNode
 */
const EditPageList = () => {
  const {
    off: {
      editPage
    },
    appConfig: {
      page
    }
  } = useAppSelector(state => state)
  const dispatch = useAppDispatch()

  const [open, setOpen] = useState(false);
  const [edit, setEdit] = useState(false);

  const [pageData, setPageData] = useState({
    label: '',
    key: '',
    icon: icons[0]
  });

  const init = () => {
    setPageData({
      label: '',
      key: moment().format('YYYYMMDDsshhmm'),
      icon: icons[0]
    })
    setEdit(false)
  }

  const [message, setMessage] = useState('');

  const addOrEditPage = () => {
    const findIndex = page.pageList.findIndex(e => e.label === pageData.label)
    if (isEmpty(pageData.label)) {
      setMessage('还没有为页面起名称')
      return
    }
    if (!edit && findIndex !== -1) {
      setMessage('页面名称已存在')
      return
    }
    if (edit) {
      const newPageList = [...page.pageList]
      const findIndex = newPageList.findIndex(e => e.key === pageData.key)
      newPageList[findIndex] = pageData
      console.log('newPageList', newPageList);

      dispatch(appConfigActions.updataPage({
        pageList: newPageList
      }))
    } else {
      dispatch(appConfigActions.updataPage({
        pageList: [
          ...page.pageList,
          pageData,
        ]
      }))
    }
    init()
  }

  /**
   * 添加或者编辑
   * @returns ReactNode
   */

  const addAndEdit = () => {
    return (
      <CSSTransition
        in={open}
        timeout={500}
        classNames="page-item"
        unmountOnExit
      >
        <div className={styles.addEditBox}>
          <div className="flex gap-2">
            <div className="flex-1">
              <input
                className="w-full appNearBg rounded-lg px-4 py-1"
                aria-label="label"
                value={pageData.label}
                onChange={(e) => {
                  if (!isEmpty(e.target.value)) {
                    setMessage('')
                  }
                  setPageData({
                    ...pageData,
                    label: e.target.value
                  })
                }} type="text"
              />
            </div>
            <div
              className="w-8 flex justify-center items-center appNearBg rounded-lg cursor-pointer active:text-yellow-500"
              onClick={() => {
                addOrEditPage()
              }}
            >
              <Icon icon="check" />
            </div>
          </div>
          {message && (
            <div className="text-red-500 text-sm mt-1">{message}</div>
          )}
          <div className={styles.icons}>
            {icons.map(e => {
              return (
                <div
                  key={e}
                  className={getClassNames([
                    styles.iconsItem,
                    {
                      [styles.iconsItemChecked]: pageData.icon === e
                    },
                  ])}
                  onClick={() => {
                    setPageData({
                      ...pageData,
                      icon: e,
                    })
                  }}
                >
                  <Icon icon={e} />
                </div>
              )
            })}
          </div>
        </div>
      </CSSTransition>
    )
  }

  useEffect(() => {
    init()
    setOpen(false)
  }, [editPage])

  return (
    <AppPortal
      visible={editPage}
      contentMobileAdaptation={false}
      position="right"
      onClose={() => {
        dispatch(offActions.update({
          editPage: false
        }))
      }}
    >
      <div className={styles.EditPageList}>
        <Content
          editClick={(info) => {
            setPageData(info)
            setOpen(true)
            setEdit(true)
          }}
        />
        {addAndEdit()}
        <div className={styles.add}>
          <div className={getClassNames([
            styles.addContent,
            {
              [styles.addContentOpen]: open
            }
          ])}>
            <Icon
              size={20}
              icon="plus"
              onClick={() => {
                init()
                setOpen(!open)
              }}
            />
          </div>
        </div>
      </div>
    </AppPortal>
  )
}

export default EditPageList